package org.xelnaga.defiler.web.controller.contentlet;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xelnaga.defiler.domain.ContentContainerModel;
import org.xelnaga.defiler.domain.ContentPriceModel;
import org.xelnaga.defiler.domain.ContentletModel;
import org.xelnaga.defiler.domain.FieldWrapper;
import org.xelnaga.defiler.domain.FileAssetModel;
import org.xelnaga.defiler.domain.StructureModel;
import org.xelnaga.defiler.domain.StructureModel.SystemStructureEnum;
import org.xelnaga.defiler.service.ContentContainerService;
import org.xelnaga.defiler.service.ContentPriceService;
import org.xelnaga.defiler.service.ContentletRelationships;
import org.xelnaga.defiler.service.ContentletService;
import org.xelnaga.defiler.service.FileAssetService;
import org.xelnaga.defiler.service.RelationshipService;

/**
 * Controller whose handler methods expect the primary key or an unique field, if any, 
 * to be present in the contentletForm.
 * 
 * This value is used to load the corresponding contentlet instance to either show or delete it.
 *
 * Note: This controller name is forced only to minimize the risks of name collisions with
 * controllers written by hands. The name is anyway not used since controllers sit on top 
 * of everything else. 
 */
@Controller("generatedContentletController")
@RequestMapping({
    "/domain/contentlet/show",
    "/domain/contentlet/confirmDelete",
    "/domain/contentlet/defaultFile",
    "/domain/contentlet/delete" })
public class ContentletController {
    //--------------------------------------------
    // Dependency Injection
    //--------------------------------------------
	@Autowired
	protected FileAssetService fileAssetService;
    @Autowired
    private ContentletWebSupport contentletWebSupport;
    @Autowired
    private ContentletService contentletManager;
    @Autowired
    private RelationshipService relationshipService;
    @Autowired
    private ContentPriceService contentPriceService;
    @Autowired
    private ContentContainerService contentContainerService;
    @InitBinder
    public void initDataBinder(WebDataBinder binder){
        binder.setAllowedFields(new String[]{"contentlet.inode"});
    }

    /**
     * Lookups the corresponding ContentletModel instance and returns it.
     * Note: Since this method is annotated with @ModelAttribute, it will be executed
     * before the chosen @RequestMapping annotated handler method.
     */
    @ModelAttribute("contentlet")
    protected ContentletModel find(@ModelAttribute ContentletForm contentletForm) {
    	ContentletModel cotent = contentletForm.getContentlet();
    	return contentletManager.get(cotent);
    }

    /**
     * Simply returns the showViewName that should render the ContentletModel instance 
     * loaded by the find method.
     */
    @RequestMapping
    public String show(@ModelAttribute("contentlet") ContentletModel contentlet, Model model) {
    	StructureModel structure = contentlet.getStructure();
    	//Show relationships and relating contentlet.
    	if(null != structure) {
    		List<FieldWrapper> result = contentletWebSupport.getContentletFieldValues(contentlet);//hold the contentlet structure field value.
    		model.addAttribute("fields", result);
    		
    		ContentletRelationships<ContentletModel> contentletRelationships = relationshipService.getRelationshipsData(contentlet);
    		model.addAttribute("contentletRelationships", contentletRelationships);
    		
    		ContentletRelationships<FileAssetModel> fileAssetRelations = relationshipService.getRelationshipsDataWithFileAsset(contentlet);
    		model.addAttribute("contentletFileAssetRelationships", fileAssetRelations);
   		
    		ContentContainerModel example = new ContentContainerModel();
    		example.setContentletInode(contentlet.getInode());
    		List<ContentContainerModel> contentContainers = contentContainerService.getListByStructureContentlet(contentlet.getInode(), contentlet.getStructureInode());
    		model.addAttribute("contentContainers", contentContainers);
    		
    		ContentPriceModel priceModel = new ContentPriceModel();
    		priceModel.setContentlet(contentlet);
			List<ContentPriceModel> priceList = contentPriceService.find(priceModel, null);
			model.addAttribute("prices", priceList);
    	}
    	
    	
        return showViewName;
    }


    /**
     * Simply load the ContentletModel instance return the confirmDeleteViewName.
     * The view should display a message to confirm the deletion.
     * For more advanced flow, you should use Spring Webflow.
     */
    @RequestMapping
    public String confirmDelete(@ModelAttribute("contentlet") ContentletModel contentlet) {
        return confirmDeleteViewName;
    }

    /**
     * Delete the ContentletModel instance loaded by the find method and return the deleteViewName;
     */
    @RequestMapping
    public String delete(@ModelAttribute("contentlet") ContentletModel contentlet) {
        contentletManager.delete(contentlet);
        return deleteViewName;
    }
    
    @RequestMapping
    public String defaultFile(@ModelAttribute("contentlet") ContentletModel contentlet, HttpServletRequest request, Model model) {
    	String fileInode = request.getParameter("fileAssetInode");
    	String type = request.getParameter("type");
    	if(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(fileInode)) {
    		FileAssetModel fileAsset = fileAssetService.getByPrimaryKey(Long.valueOf(fileInode));
    		if(null != fileAsset) {
	    		SystemStructureEnum structure = StructureModel.SystemStructureEnum.getInstance(Integer.valueOf(type));
	    		//设置默认封面图
	    		if(null != structure && structure == SystemStructureEnum.CoverFileAsset) {
	    			contentlet.setFileAsset(fileAsset);
	    		} else {
	    			contentlet.setIconFileAsset(fileAsset);
	    		}
	    		contentletManager.update(contentlet);
    		}
    	}
    	model.addAttribute("contentlet.inode", contentlet.getInode());
    	return "redirect:/domain/contentlet/show";
    }
    //--------------------------------------------
    // Returned view configuration
    //--------------------------------------------
    private String showViewName = "domain/contentlet/show";

    public void setShowViewName(String showViewName) {
        this.showViewName = showViewName;
    }

    private String confirmDeleteViewName = "domain/contentlet/confirmDelete";

    public void setConfirmDeleteViewName(String confirmDeleteViewName) {
        this.confirmDeleteViewName = confirmDeleteViewName;
    }

    private String deleteViewName = "redirect:/domain/contentlet/index";

    public void setDeleteViewName(String deleteViewName) {
        this.deleteViewName = deleteViewName;
    }

}
